import sys
import os
#from PIL import Image
#import easyocr
#import cv2
# using time module
import time
import re
# import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


# from msedge.selenium_tools import EdgeOptions
# options = webdriver.EdgeOptions()
# options = EdgeOptions()
# options.use_chromium = True
# Here you set the path of the profile ending with User Data not the profile folder
# options.add_argument("user-data-dir=C:\\Users\\Thinkpad\\AppData\\Local\\Microsoft\\Edge\\User Data");
# Here you specify the actual profile folder
# options.add_argument("profile-directory=Profile 1");
# options.binary_location = r"e:\selenium\msedgedriver.exe"

class Engine:
	def __init__(self):
    # Add options if needed	
		options = Options()
#        options.add_argument("--headless=new")
		options.add_argument("--headless")  # Run in headless mode
		options.add_argument("--disable-gpu")  # Disable GPU acceleration
		options.add_argument(f"--window-size=1366,768")
		options.add_argument(f'--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36')
		options.add_argument('--disable-blink-features=AutomationControlled')
		options.add_argument("--disable-extensions")
#		options.add_argument("--proxy-server='direct://'")
#		options.add_argument("--proxy-bypass-list=*")
		options.add_argument('--ignore-certificate-errors')
		options.add_argument("--password-store=basic")
		options.add_argument("--no-sandbox")
		options.add_argument("--disable-dev-shm-usage")
		options.add_argument("--disable-extensions")
		options.add_argument("--enable-automation")
		options.add_argument("--disable-browser-side-navigation")
		options.add_argument("--disable-web-security")
		options.add_argument("--disable-dev-shm-usage")
		options.add_argument("--disable-infobars")
		options.add_argument("--disable-gpu")
		options.add_argument("--disable-setuid-sandbox")
		options.add_argument("--disable-software-rasterizer")
		options.add_argument("--profile-directory=work");
#		options.add_argument(f"--user-data-dir=PATH_TO_CHROME_PROFILE")
#		options.add_argument('--proxy-server=IP_ADRESS:PORT')
		options.add_argument('--ignore-certificate-errors')
		options.add_argument("--no-sandbox");
		options.add_argument("--remote-debugging-port=8000")
		service = Service(r'e:\chrome-win64\chrome.exe')
        # enter keyword to search
        # driver = webdriver.Edge(options)
        # Create an instance of Undetected ChromeDriver with options		
		self.driver = webdriver.Chrome(options=options)
		self.original_size = self.driver.get_window_size()
		
	def save_as_image(self, url, fn):
		self.driver.get(url)
        # Resize window to capture full page

		required_width = self.driver.execute_script('return document.body.parentNode.scrollWidth')
		required_height = self.driver.execute_script('return document.body.parentNode.scrollHeight')
		self.driver.set_window_size(required_width, required_height)
        # Capture the screenshot
		self.driver.get_screenshot_as_file(fn)
		
	def restore_win_size(self):
        # Revert to original window size
		self.driver.set_window_size(self.original_size['width'], self.original_size['height'])


def test(driver):
    a = driver.find_element(By.CLASS_NAME, "idxHeading")
    print(a.text)
    a = driver.find_elements(By.CLASS_NAME, "idxHeading")
    for x in a:
        print(x.text)

    a = driver.find_element(By.CLASS_NAME, "idxRow")
    print(a.text)

    a = driver.find_elements(By.CLASS_NAME, "idxRow")
    for x in a:
        print(x.text)
        children = x.find_elements(By.TAG_NAME, "a")
        for y in children:
            l = y.get_attribute('href')
            print(l)

def crop(image_path,box):
	image= Image.open(image_path)
	crop = image.crop(box)
	return crop.save(image_path, 'PNG')

if len(sys.argv) < 2:
    sys.exit(0)

e = Engine()
driver = e.driver
class_task=[]
pkg_task = [sys.argv[1]]
while len(pkg_task) > 0:
    url = pkg_task.pop()
    driver.get(url)

#    test(driver)
    elements = driver.find_elements(By.XPATH, "//*[@class='idxRow']")
    for x in elements:        
        title=x.text
#        print(title)
        children = x.find_elements(By.TAG_NAME, "a")
        for a in children:
            l = a.get_attribute('href')
            if l.endswith("java.htm"):
                class_task.append([l,title])
#                    print(l,title)
            else:
                pkg_task.append(l)

#reader = easyocr.Reader(['en'])
#img_fn="~tmp.png"
for t in class_task:
	fn="%s.java"%t[1]
	if os.path.exists(fn):
		ts= time.time()
		fn="%s_%d.java"%(t[1],int(ts))
	
#	e.save_as_image(t[0],img_fn)
	driver.get(t[0])
	c = driver.find_element(By.ID, "contentColumn")
	lines= c.text.split("\n")			
#	print(c.location,c.size)
#	box = (c.location["x"], c.location["y"], c.size["width"], c.size["height"]+10)
#	print(box)
#	crop(img_fn,box)
#	img = cv2.imread(img_fn)
#	result = reader.readtext(img, detail = 0, paragraph  = True)
	
	with open(fn,"w+t", encoding='utf-8') as f:	
		for l in lines:
			l = re.sub(r'^(\d)+', '', l)	
			l = l.replace("JavaDoc",'')
			print(l,file=f)	
#		for p in result:
#			print(" ".join(p).encode('utf-8'),file=f)

			
	


	
# Close the driver
driver.quit()
